import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-form-data',
  templateUrl: './form-data.component.html',
  styleUrls: ['./form-data.component.css']
})
export class FormDataComponent implements OnInit {

  form: FormGroup;
  fieldBase: any[];

  formTemplateXml = `[
  {
    "name": "text",
    "id": "text",
    "required": true,
    "isMultiple": false,
    "type": "text",
    "value": "中文ID名称"
  },
  {
    "name": "radio",
    "id": "radio",
    "required": true,
    "isMultiple": false,
    "type": "radio",
    "dataSource":"0",
    "dataSourceData":["a","b","c","d"],
    "value": {
      "label":"a",
      "value":"a"
    }
  },
  {
    "name": "select",
    "id": "select",
    "required": true,
    "isMultiple": false,
    "type": "select",
    "value": {},
    "dataSource":"2",
    "dataSourceData":"http://localhost:8080/formData"
  },
  {
    "name": "money",
    "id": "money",
    "required": true,
    "isMultiple": false,
    "type": "text",
    "value": 30000
  }
]`;


  constructor(private fb: FormBuilder,
              private http: HttpClient) {
  }

  ngOnInit() {
    this.form = this.fb.group({});
    this.fieldBase = JSON.parse(this.formTemplateXml);
    this.fieldBase.forEach(field => {
      if (field.dataSource === '2') {
        this.getDataSourceData(field.dataSourceData).subscribe(res => {
          field._dataSourceOption = res;
        });
      }
      this.form.addControl(field.id, this.fb.control(field.value));
    });
  }

  private getDataSourceData(url: string): Observable<any> {
    return this.http.get(url);
  }

}
